<template>
  <div class="role-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>角色管理</span>
          <el-button type="primary" @click="handleAdd">添加角色</el-button>
        </div>
      </template>
      
      <!-- 搜索区域 -->
      <div class="search-container">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="搜索">
            <el-input
              v-model="searchForm.search"
              placeholder="角色名称/编码"
              clearable
              @keyup.enter="handleSearch"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 角色列表 -->
      <el-table
        :data="roleList"
        v-loading="loading"
        border
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="角色名称" width="150" />
        <el-table-column prop="code" label="角色编码" width="120" />
        <el-table-column prop="description" label="描述" />
        <el-table-column label="权限数量" width="100">
          <template #default="{ row }">
            <el-tag type="info">{{ row.permissions?.length || 0 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="菜单数量" width="100">
          <template #default="{ row }">
            <el-tag type="info">{{ row.menus?.length || 0 }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="warning" @click="handlePermissions(row)">权限</el-button>
            <el-button size="small" type="info" @click="handleMenus(row)">菜单</el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(row)"
              :disabled="row.code === 'admin'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.per_page"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 角色表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleRules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="roleForm.code" :disabled="isEdit" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入角色描述"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 对话框 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="分配权限"
      width="600px"
    >
      <el-transfer
        v-model="selectedPermissions"
        :data="permissionList"
        :titles="['可选权限', '已选权限']"
        :props="{
          key: 'id',
          label: 'name'
        }"
        filterable
      />
      
      <template #footer>
        <el-button @click="permissionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAssignPermissions" :loading="assignLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 菜单分配对话框 -->
    <el-dialog
      v-model="menuDialogVisible"
      title="分配菜单"
      width="600px"
    >
      <el-tree
        ref="menuTreeRef"
        :data="menuList"
        :props="{
          children: 'children',
          label: 'title'
        }"
        show-checkbox
        node-key="id"
        :default-checked-keys="selectedMenus"
      />
      
      <template #footer>
        <el-button @click="menuDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAssignMenus" :loading="assignLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getRoleList, createRole, updateRole, deleteRole, assignPermissions, assignMenus } from '@/api/roles'
import { getPermissionList } from '@/api/permissions'
import { getMenuList } from '@/api/menus'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const assignLoading = ref(false)
const dialogVisible = ref(false)
const permissionDialogVisible = ref(false)
const menuDialogVisible = ref(false)
const isEdit = ref(false)
const roleFormRef = ref()
const menuTreeRef = ref()

// 列表数据
const roleList = ref([])
const permissionList = ref([])
const menuList = ref([])

// 搜索表单
const searchForm = reactive({
  search: ''
})

// 分页数据
const pagination = reactive({
  page: 1,
  per_page: 10,
  total: 0
})

// 角色表单
const roleForm = reactive({
  name: '',
  code: '',
  description: ''
})

// 表单验证规则
const roleRules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '角色编码只能包含字母、数字和下划线', trigger: 'blur' }
  ]
}

// 相关
const selectedPermissions = ref([])
const selectedMenus = ref([])
const currentRole = ref(null)

// 计算属性
const dialogTitle = computed(() => isEdit.value ? '编辑角色' : '添加角色')

// 获取角色列表
const fetchRoleList = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.page,
      per_page: pagination.per_page,
      search: searchForm.search
    }
    const response = await getRoleList(params)
    roleList.value = response.data.roles
    pagination.total = response.data.pagination.total
  } catch (error) {
    ElMessage.error('获取角色列表失败')
  } finally {
    loading.value = false
  }
}

// 获取权限列表
const fetchPermissionList = async () => {
  try {
    const response = await getPermissionList()
    permissionList.value = response.data.permissions.map(item => ({
      id: item.id,
      name: `${item.name} (${item.code})`
    }))
  } catch (error) {
    ElMessage.error('获取权限列表失败')
  }
}

// 获取菜单列表
const fetchMenuList = async () => {
  try {
    const response = await getMenuList()
    menuList.value = response.data.menus
  } catch (error) {
    ElMessage.error('获取菜单列表失败')
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchRoleList()
}

// 重置搜索
const handleReset = () => {
  searchForm.search = ''
  pagination.page = 1
  fetchRoleList()
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.per_page = size
  pagination.page = 1
  fetchRoleList()
}

const handleCurrentChange = (page) => {
  pagination.page = page
  fetchRoleList()
}

// 添加角色
const handleAdd = () => {
  isEdit.value = false
  dialogVisible.value = true
}

// 编辑角色
const handleEdit = (row) => {
  isEdit.value = true
  Object.assign(roleForm, {
    id: row.id,
    name: row.name,
    code: row.code,
    description: row.description
  })
  dialogVisible.value = true
}

// 删除角色
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除角色 "${row.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteRole(row.id)
    ElMessage.success('删除成功')
    fetchRoleList()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 分配权限
const handlePermissions = (row) => {
  currentRole.value = row
  selectedPermissions.value = row.permissions?.map(p => p.id) || []
  permissionDialogVisible.value = true
}

// 分配菜单
const handleMenus = (row) => {
  currentRole.value = row
  selectedMenus.value = row.menus?.map(m => m.id) || []
  menuDialogVisible.value = true
}

// 提交角色表单
const handleSubmit = async () => {
  try {
    await roleFormRef.value.validate()
    submitLoading.value = true
    
    if (isEdit.value) {
      await updateRole(roleForm.id, roleForm)
      ElMessage.success('更新成功')
    } else {
      await createRole(roleForm)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    fetchRoleList()
  } catch (error) {
    ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
  } finally {
    submitLoading.value = false
  }
}

// 提交权限分配
const handleAssignPermissions = async () => {
  try {
    assignLoading.value = true
    await assignPermissions(currentRole.value.id, selectedPermissions.value)
    ElMessage.success('权限分配成功')
    permissionDialogVisible.value = false
    await fetchRoleList()
  } catch (error) {
    ElMessage.error('权限分配失败')
  } finally {
    assignLoading.value = false
  }
}

// 提交菜单分配
const handleAssignMenus = async () => {
  try {
    assignLoading.value = true
    const checkedKeys = menuTreeRef.value.getCheckedKeys()
    await assignMenus(currentRole.value.id, checkedKeys)
    ElMessage.success('菜单分配成功')
    menuDialogVisible.value = false
    fetchRoleList()
  } catch (error) {
    ElMessage.error('菜单分配失败')
  } finally {
    assignLoading.value = false
  }
}

// 重置表单
const resetForm = () => {
  roleFormRef.value?.resetFields()
  Object.assign(roleForm, {
    name: '',
    code: '',
    description: ''
  })
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  return new Date(dateStr).toLocaleString()
}

onMounted(() => {
  fetchRoleList()
  fetchPermissionList()
  fetchMenuList()
})
</script>

<style scoped>
.role-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-container {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style> 